<template>
  <div class="count">
    <!-- 地址 -->
    <view class="addr" @tap="chooseAddr">
      <block v-if="addrInfo.userName">
        <view class="content">
          <view class="username">收件人：{{addrInfo.userName}} {{addrInfo.telNumber}}</view>
          <view class="addr-info">收货地址：{{addrInfo.addressInfo}}</view>
        </view>
      </block>
      <block v-else>
        <view class="content">请添加收货地址</view>
      </block>
    </view>

    <!-- 购物车项 -->
    <view class="cart">
      <view class="cart-bar">
        <i class="iconfont icon-gouwuche"></i>
        <view class="cart-shop">优购生活馆</view>
      </view>
      <view class="cart-content">
        <view class="cart-item">
            <div class="item-inner" v-for="(value, key) of cartList" :key="key" @tap="gotoDetail(key)">
              <i class="iconfont icon-zhuanzhangchenggong" :class="{ 'selected':value.isSelect }" @tap.stop="handleChangeItem(key)"></i>
              <image
                class="item-img"
                :src="value.goods_small_logo"
                mode="aspectFill"
                lazy-load="false">
              </image>
              <div class="item-info">
                <div class="title">{{value.goods_name}}</div>
                <div class="content">
                  <div class="price">￥{{value.goods_price}}</div>
                  <div class="num">
                    <div class="sub opt" @tap.stop="handleOpt(key, -1)">-</div>
                    <view type="text" class="num-in">{{value.count}}</view>
                    <div class="plus opt" @tap.stop="handleOpt(key, 1)">+</div>
                  </div>
                </div>
              </div>
            </div>
        </view>
      </view>
    </view>

    <!-- 结算 -->
    <view class="count-bar">
        <div class="count-inner">
          <div class="select-all">
            <i class="iconfont icon-zhuanzhangchenggong" :class="{ 'selected':isSelectAll }" @tap="handleChangeAll"></i>
            <div class="text">全选</div>
          </div>
          <view class="count-all">
            <div class="price-all">合计：￥{{totalPrice}}</div>
            <div class="delivery">包含运费</div>
          </view>
          <button class="count-final" @tap="toPay">结算({{totalCount}})</button>
        </div>

    </view>
  </div>
</template>

<script>

export default {
  data () {
    return {
      addrInfo: {}, // 地址信息
      cartList: {}, // 购物车数据
      selectList: [], // 选择的商品
      // isSelectAll: true // 是否全选
    }
  },
  onLoad () {
    this.initPage()
  },
  computed: {
    // 全部价格
    totalPrice: function () {
      let total = 0;
      for (let i in this.cartList) {
        if (this.cartList[i].isSelect) {
          total += this.cartList[i].count * this.cartList[i].goods_price;
        }
      }
      return total.toFixed(2);
    },
    // 是否全选
    isSelectAll: function () {
      let all = true;
      for (let i in this.cartList) {
        if (!this.cartList[i].isSelect) {
          all = false;
        }
      }
      return all;
    },
    // 结算总数量
    totalCount: function () {
      let all = 0;
      for (let i in this.cartList) {
        if (this.cartList[i].isSelect) {
          all++;
        }
      }
      return all;
    }
  },
  methods: {
    // 选择地址
    chooseAddr () {
      // 调用微信小程序自带的收货地址功能
      wx.chooseAddress({
        success: res => {
          // 传统赋值写法
          // let userName = res.userName;
          // 解构赋值写法 - 和上一行代码功能相同
          // let { userName } = res;
          let { userName,provinceName,cityName,countyName,detailInfo,telNumber } = res;
          // 拼接收获地址
          this.addrInfo = {
            userName,
            telNumber,
            addressInfo:`${provinceName}${cityName}${countyName}${detailInfo}`
          }
          // 把数据存储到本地
          wx.setStorageSync('addr-info',this.addrInfo);
        }
      });
    },
    // 添加与减少
    handleOpt (key, num) {
      if ((num < 0) && (this.cartList[key].count === 1)) {
        wx.showModal({
          title: '注意', //提示的标题,
          content: '继续操作将删除此商品，是否继续？', //提示的内容,
          showCancel: true, //是否显示取消按钮,
          cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
          cancelColor: '#666', //取消按钮的文字颜色,
          confirmText: '删除', //确定按钮的文字，默认为取消，最多 4 个字符,
          confirmColor: '#ff2d49', //确定按钮的文字颜色,
          success: res => {
            if (res.confirm) {
              delete this.cartList[key]
              this.cartList = JSON.parse(JSON.stringify(this.cartList))
              // 保存
              wx.setStorageSync('cart-list', this.cartList)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        });
      } else {
        // 根据传入的num进行加减操作
        this.cartList[key].count += num;
        // 保存
        wx.setStorageSync('cart-list', this.cartList)
      }
    },
    // 选择商品
    handleChangeItem (key) {
      // console.log(key)
      this.cartList[key].isSelect = !this.cartList[key].isSelect
      // 保存
      wx.setStorageSync('cart-list', this.cartList)
    },
    // 全选
    handleChangeAll () {
      let isAll = this.isSelectAll;
      for (let i in this.cartList) {
        if (isAll) {
          this.cartList[i].isSelect = false;
        } else {
          this.cartList[i].isSelect = true;
        }
      }
      // 保存
      wx.setStorageSync('cart-list', this.cartList)
    },
    // 初始化页面
    initPage () {
      // 加载页面获取地址信息
      this.addrInfo = wx.getStorageSync('addr-info') || {};
      // 本地缓存的购物车数据
      this.cartList = wx.getStorageSync('cart-list') || {};
    },
    // 点击跳转到商品详情
    gotoDetail(id){
      wx.navigateTo({ url: '/pages/goodsdetail/main?goods_id='+id });
    },
    // 去结算
    toPay () {
      if (this.totalCount === 0) {
        wx.showToast({
          title: '请勾选商品', //提示的内容,
          icon: 'none', //图标,
          duration: 2000, //延迟时间,
          mask: false, //显示透明蒙层，防止触摸穿透,
          success: res => {}
        });
        return;
      }
      wx.navigateTo({ url: '/pages/pay/main' });
    }
  },
  // 下拉刷新
  onPullDownRefresh () {
    this.initPage()
    wx.stopPullDownRefresh()
  }
}
</script>

<style lang="scss" scoped>
.iconfont {
  font-size: 40rpx;
}
.selected {
  color: #ff2d49;
}
.count {
  background-color: #f4f4f4;
}
.addr {
  padding: 20rpx;
  color: #666;
  font-size: 28rpx;
  background-color: #fff;
  border-bottom: 15rpx dashed #ff2d49;
  .content {
    position: relative;
    background-color: #fff;
    &::after {
      content: '修改 〉';
      position: absolute;
      top: 10rpx;
      right: 0;
      font-size: 24rpx;
      color: #ff2d49;
    }
    .username {
      height: 60rpx;
      line-height: 60rpx;
    }
    .addr-info {
      height: 60rpx;
      line-height: 60rpx;
    }
  }
}
.cart {
  margin-top: 20rpx;
  padding-bottom: 100rpx;
  font-size: 30rpx;
  background-color: #fff;
  .cart-bar {
    padding: 20rpx;
    display: flex;
    height: 70rpx;
    line-height: 70rpx;
    border-bottom: 1rpx solid #ddd;
    i {
      padding: 0 20rpx;
      color: #ff2d49;
      font-size: 40rpx;
      font-weight: bold;
    }
  }
  .cart-content {
    .cart-item {
      .item-inner {
        height: 200rpx;
        display: flex;
        align-items: center;
        padding: 10rpx 20rpx;
        border-bottom: 1rpx solid #f4f4f4;
        image {
          width: 180rpx;
          height: 180rpx;
          padding: 0 20rpx;
        }
        .item-info {
          height: 180rpx;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .title {
            font-size: 28rpx;
            // margin-bottom: 20rpx;
            // 两行换行
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }
          .content {
            display: flex;
            justify-content: space-between;
            .price {
              font-size: 34rpx;
              color: #ff2d49;
            }
            .num {
              display: flex;
              background-color: #eee;
              .num-in, .opt {
                display: block;
                width: 60rpx;
                text-align: center;
                background-color: #f4f4f4;
              }
              .num-in {
                background-color: #fff;
              }
            }
          }
        }
      }
    }
  }
}
.count-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  // padding: 10rpx 0;
  font-size: 28rpx;
  .count-inner {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100rpx;
    .select-all {
      padding-left: 20rpx;
      display: flex;
      align-items: center;
      i {
        padding-right: 20rpx;
      } 
    }
    .count-all {
      .price-all {
        color: #ff2d49;
      }
      .delivery {
        color: #aaa;
      }
    }
    .count-final {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      background-color: #ff2d49;
      width: 33.33%;
      height: 100%;
      margin: 0;
      border-radius: 0;
      font-size: 30rpx;
    }
    .button-hover {
      background-color: #c55;
    }
  }
}
</style>
